import { createRow, createCell } from '../../../utils/create-table';

const Commands = {
  insertTableRow(editor, cellNode) {
    const { document } = editor.value;
    const rowNode = document.getParent(cellNode.key);
    const columnSize = rowNode.nodes.size;
    const newRowNode = createRow(columnSize);
    const insertPath = document.getNextPath(rowNode.key);
    editor.insertNodeByPath(newRowNode, insertPath);
  },
  deleteTableRow(editor, cellNode) {
    const { document } = editor.value;
    const rowNode = document.getParent(cellNode.key);
    editor.removeNode(rowNode.key);
  },
  insertTableCell(editor, cellNode) {
    const { document } = editor.value;
    const rowNode = document.getParent(cellNode.key);
    const tableNode = document.getParent(rowNode.key);
    const columnIndex = rowNode.nodes.indexOf(cellNode);
    tableNode.nodes.forEach(row => {
      const newcellNode = createCell();
      const insertPath = document.getPath(row.key);
      editor.insertNodeByPath(newcellNode, insertPath.concat(columnIndex));
    });
  },
  deleteTableCell(editor, cellNode) {
    const { document } = editor.value;
    const rowNode = document.getParent(cellNode.key);
    const tableNode = document.getParent(rowNode.key);
    const columnIndex = rowNode.nodes.indexOf(cellNode);
    tableNode.nodes.forEach(row => {
      const cell = row.nodes.get(columnIndex);
      if (cell) {
        editor.removeNode(cell.key);
      }
    });
  },
};

export default Commands;
